<!-- custom-tab-bar/index.vue -->
<template>
	<div class="custom-tab-bar">
		<div
			v-for="(item, index) in tabList"
			:key="index"
			class="tab-item"
			:class="{ active: activeIndex === index }"
			@click="handleTabClick(item.pagePath, index)"
		>
			{{ item.text }}
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import pagesConfig from '@/pages.json';

interface TabItem {
	pagePath: string;
	text: string;
	iconPath?: string;
	selectedIconPath?: string;
}

const tabList = ref<TabItem[]>([]);

const activeIndex = ref(0); // 当前选中索引

// 初始化 TabBar 配置
const initTabList = () => {
	tabList.value = pagesConfig.tabBar.list || [];
};

// 切换 Tab
const handleTabClick = (pagePath: string, index: number) => {
	activeIndex.value = index;
	uni.switchTab({ url: `/${pagePath}` });
};

// 同步选中状态
const syncActiveIndex = () => {
	const currentPage = getCurrentPages().pop()?.route || '';
	activeIndex.value = tabList.value.findIndex(
		item => `/${item.pagePath}` === `/${currentPage}`,
	);
};

// 生命周期
onMounted(() => {
	initTabList();
	syncActiveIndex(); // 初始化时同步一次
});

// 监听页面显示（解决返回页面时状态不同步）
onShow(() => {
	syncActiveIndex();
});
</script>

<style scoped>
/* 样式与原方案保持一致 */
.custom-tab-bar,
uni-tabbar {
	position: fixed;
	bottom: calc(var(--window-bottom) + 10px);
	left: 0;
	right: 0;
	height: 50px;
	display: flex;
	background-color: #fff;
	border-top: 1px solid #eee;
}
.tab-item {
	flex: 1;
	text-align: center;
	line-height: 50px;
}
.active {
	color: #007aff;
}
</style>
